package com.miyu.system.controller.sys;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson.JSONObject;
import com.miyu.common.utils.commonUtils.RedisCache;
import com.miyu.system.service.sys.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/system/user")
public class UserLogin {
    @Autowired
    private UserService userService;

    @RequestMapping("userLogin")
    public JSONObject userLogin(@RequestBody JSONObject param){
        JSONObject rs = userService.userLogin(param);
        return  rs;
    }
    /**
     * 登录验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("checkImg")
    public HttpServletResponse checkImg(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(150, 50, 4, 20);
        String code = captcha.getCode();
        captcha.createImage( captcha.getCode());
        String ip = getIpAddr(request);
        //图形验证码写出，可以写出到文件，也可以写出到流
        JSONObject joo = new JSONObject();
        joo.put("ip",ip);
        joo.put("code",code);
        ip=ip.replace(".","");
        RedisCache.set(ip+"_CheckImgCode",code,300);
        captcha.write(response.getOutputStream());
        return null;
    }
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip!=null|| ip.length() >0){
            String[]  ipStr =ip.split(",");
            ip=ipStr[0];
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 用户退出
     * @param param
     * @return
     */
    @RequestMapping("loginOut")
    public JSONObject loginOut(@RequestBody  JSONObject param){
        return userService.userloginOut(param);
    }

}


